﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Configuration;
using System.IO;
using LeadExpress.Models.ViewPages;

namespace LeadExpress.Areas.Management.Controllers
{
    public class ProductListController : Controller
    {
        private static string fileName = "";
        public static string staFileName
        {
            get { return fileName; }
            set { fileName = value; }
        }

        // Create an instance of user manage
        LeadExpress.Repository.ProductManagementRepository repository = new LeadExpress.Repository.ProductManagementRepository();
        public static string ProductImagesURL = ConfigurationManager.AppSettings["ProductImagesURL"].ToString();

        // GET: /Management/Home/
        [Authorize(Roles = "SuperAdministrator")]
        public ActionResult Index()
        {
            ProductManagementModel model = new ProductManagementModel();
            model = repository.GetModel(Helpers.Constant.HOME, "SuperAdministrator", 10, 1);

            return View(model);
        }

        // GET: /Management/Product/Search?keywords=tt&fieldName=type
        [Authorize(Roles = "SuperAdministrator")]
        public ActionResult Search(string keywords, string fieldName)
        {
            ProductManagementModel model = new ProductManagementModel();
            model = repository.GetModel(Helpers.Constant.HOME, "SuperAdministrator", keywords, fieldName, 10, 1);
            model.Keywords = keywords;
            model.FieldName = fieldName;

            return View(model);
        }


        [HttpPost]
        [Authorize(Roles = "SuperAdministrator")]
        public ActionResult Fillter(string keywords, string startDate, string endDate, string categoryId, string stateId, int pageSize, int pageIndex, int id, string sortBy, string sortOrder)
        {
            ProductManagementModel model = new ProductManagementModel();
            string[] categories = categoryId.Split(',');
            string[] states = stateId.Split(',');

            model = repository.GetModel(Helpers.Constant.HOME, "SuperAdministrator", keywords, startDate, endDate, categories, states, sortBy, sortOrder, pageSize, pageIndex, id);

            return Json(model);
        }


        [HttpPost]
        [Authorize(Roles = "SuperAdministrator")]
        public ActionResult SearchFillter(string keywords, string fieldName, int pageSize, int pageIndex)
        {
            ProductManagementModel model = new ProductManagementModel();
            model = repository.GetModelSearch(keywords, fieldName, pageSize, pageIndex);
            model.Keywords = keywords;
            model.FieldName = fieldName;

            return Json(model);
        }
        
        // GET: /Management/Home/
        [Authorize(Roles = "SuperAdministrator")]
        public ActionResult Add()
        {
            ProductManagementModel model = new ProductManagementModel();
            model = repository.GetModel(Helpers.Constant.HOME, "SuperAdministrator", 0);

            return View(model);
        }

        [HttpPost]
        [ValidateInput(false)]
        [Authorize(Roles = "SuperAdministrator")]
        public ActionResult Add(FormCollection form)
        {
            Product model = new Product();

            model.Title = form["Title"].ToString();
            model.ImageURL = form["ImageURL"].ToString();
            model.ShortDesc = form["ShortDesc"].ToString();
            model.LongDesc = form["LongDesc"].ToString();
            model.MetaKeywords = form["MetaKeywords"].ToString();
            model.MetaDescription = form["MetaDescription"].ToString();

            // Start Date
            DateTime isStartDate;
            if (form["StartDate"] != null && DateTime.TryParse(form["StartDate"].ToString(), out isStartDate))
            {
                model.StartDate = Convert.ToDateTime(form["StartDate"].ToString());
            }

            // End Date
            DateTime isEndDate;
            if (form["EndDate"] != null && DateTime.TryParse(form["EndDate"].ToString(), out isEndDate))
            {
                model.EndDate = Convert.ToDateTime(form["EndDate"].ToString());
            }

            model.IsSpecial = (form["IsSpecial"] != null && form["IsSpecial"].ToString() == "on");
            model.IsTop = (form["IsTop"] != null && form["IsTop"].ToString() == "on");
            model.Approved = (form["Approved"] != null && form["Approved"].ToString() == "on");
            model.Active = (form["Active"] != null && form["Active"].ToString() == "on");

            repository.Create(model);

            return RedirectToAction("Index", "ProductList");
        }

        [Authorize(Roles = "SuperAdministrator")]
        public ActionResult Edit(int id)
        {
            ProductManagementModel model = new ProductManagementModel();
            model = repository.GetModel(Helpers.Constant.HOME, "SuperAdministrator", id);

            ViewBag.ProductId = id;

            return View(model);
        }

        [HttpPost]
        [ValidateInput(false)]
        [Authorize(Roles = "SuperAdministrator")]
        public ActionResult Edit(int id, FormCollection form)
        {
            Product model = repository.GetSingle(id);

            if (model != null)
            {

                model.Title = form["Title"].ToString();
                model.ImageURL = form["ImageURL"].ToString();
                model.ShortDesc = form["ShortDesc"].ToString();
                model.LongDesc = form["LongDesc"].ToString();
                model.MetaKeywords = form["MetaKeywords"].ToString();
                model.MetaDescription = form["MetaDescription"].ToString();

                // Start Date
                DateTime isStartDate;
                if (form["StartDate"] != null && DateTime.TryParse(form["StartDate"].ToString(), out isStartDate))
                {
                    model.StartDate = Convert.ToDateTime(form["StartDate"].ToString());
                }

                // End Date
                DateTime isEndDate;
                if (form["EndDate"] != null && DateTime.TryParse(form["EndDate"].ToString(), out isEndDate))
                {
                    model.EndDate = Convert.ToDateTime(form["EndDate"].ToString());
                }

                model.IsSpecial = (form["IsSpecial"] != null && form["IsSpecial"].ToString() == "on");
                model.IsTop = (form["IsTop"] != null && form["IsTop"].ToString() == "on");
                model.Approved = (form["Approved"] != null && form["Approved"].ToString() == "on");
                model.Active = (form["Active"] != null && form["Active"].ToString() == "on");

                repository.Update(model);
            }

            return RedirectToAction("Index", "ProductList");
        }
        
        //[HttpPost]
        public ActionResult Upload(HttpPostedFileBase fileData)
        {
            // Verify that the user selected a file
            UserModel model = new UserModel();
            if (fileData != null && fileData.ContentLength > 0)
            {
                // extract only the fielname
                fileName = Path.GetFileName(fileData.FileName);

                // store the file inside ~/App_Data/uploads folder
                var path = Path.Combine(Server.MapPath(ProductImagesURL), fileName);
                fileData.SaveAs(path);
            }
            // redirect back to the index action to show the form once again
            return Json(model);
        }

        [HttpGet]
        [Authorize(Roles = "SuperAdministrator")]
        public ActionResult UploadComplete()
        {
            return Json(string.Format("{0}/{1}", ProductImagesURL, fileName), JsonRequestBehavior.AllowGet);
        }
    }
}
